package week9;

/**
 * Created by Administrator on 2016/4/30.
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import static java.lang.System.out;

public class ClassViewer {
    public static void main(String[] args) {
        try {
            ClassViewer.view(args[0]);
        } catch (ArrayIndexOutOfBoundsException e) {
            out.println("没有指定类");
        } catch (ClassNotFoundException e) {
            out.println("找不到指定类");
        }
    }

    public static void view(String clzName) throws ClassNotFoundException {
        Class clz = Class.forName(clzName);
        showPackageInfo(clz);
        showClassInfo(clz);
        out.println("{");
        showFiledsInfo(clz);
        showConstructorsInfo(clz);
        showMethodsInfo(clz);
        out.println("}");
    }

    private static void showPackageInfo(Class clz) {
        Package p = clz.getPackage();
        out.printf("package %s;%n", p.getName());
    }

    private static void showClassInfo(Class clz) {
        int modifier = clz.getModifiers();
        out.printf("%s %s %s", Modifier.toString(modifier), Modifier.isInterface(modifier) ? "interface" : "class", clz.getName());
    }

    private static void showFiledsInfo(Class clz) throws SecurityException {
        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            out.printf("\t%s %s %s;%n", Modifier.toString(field.getModifiers()),
                    field.getType().getName(),
                    field.getName());
        }
    }

    private static void showConstructorsInfo(Class clz) throws SecurityException {
        Constructor[] constructors = clz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            out.printf("\t%s %s();%n", Modifier.toString(constructor.getModifiers()),
                    constructor.getName());
        }
    }

    private static void showMethodsInfo(Class clz) throws SecurityException {
        Method[] methods = clz.getDeclaredMethods();
        for (Method method : methods) {
            out.printf("\t%s %s %s();%n", Modifier.toString(method.getModifiers()),
                    method.getReturnType().getName(),
                    method.getName());
        }
    }
}